package org.csu.mypetstore.web.servlets;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.Order;
import org.csu.mypetstore.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class NewOrderFormServlet extends HttpServlet {
    private static final String VIEW_newOrder = "/WEB-INF/jsp/order/NewOrderForm.jsp";
    private static final String SIGNON_FORM = "/WEB-INF/jsp/account/SignonForm.jsp";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        Account account = (Account)session.getAttribute("account");
        Cart cart = (Cart)session.getAttribute("cart");

        if (account!=null){
            Order order = new Order();
            order.initOrder(account, cart);

            session.setAttribute("order",order);


            if(account != null){
                HttpServletRequest httpRequest= req;
                String strBackUrl = "http://" + req.getServerName() + ":" + req.getServerPort()
                        + httpRequest.getContextPath() + httpRequest.getServletPath() + "?" + (httpRequest.getQueryString());

                LogService logService = new LogService();

                String logInfo = logService.logInfo(" ") + strBackUrl + " 确定订单";
                logService.insertLogInfo(account.getUsername(), logInfo);
            }

            req.getRequestDispatcher(VIEW_newOrder).forward(req,resp);
        }

        else {



            req.getRequestDispatcher(SIGNON_FORM).forward(req,resp);
        }

    }
}
